#include "Acceptor.h"
#include "TcpConnection.h"
#include "TcpServer.h"
#include <iostream>
#include <memory>
#include <unistd.h>

using std::cout;
using std::endl;
using std::cerr;
using std::shared_ptr;

#include <sys/socket.h>
Acceptor::Acceptor(EventLoop *loop, const string &ip, unsigned short port)
: _loop(loop)
, _sock()
, _addr(ip, port)
, _isListening(false)
{
}

Acceptor::~Acceptor()
{}

void Acceptor::ready()//执行地址端口复用\bind\listen
{
    setReuseAddr();
    setReusePort();
    bind();
    listen();
}

int Acceptor::accept()
{
    int fd = ::accept(_sock.fd(), nullptr, nullptr);
    if (fd == -1)
    {
        cerr << "Acceptor::accept" << endl;
        return -1;
    }
    return fd;
}
void Acceptor::setReuseAddr()
{
    int opt = 1;
    int ret = setsockopt(_sock.fd(), SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
    if (ret == -1)
    {
        cerr << "setsockopt" << endl;
        return;
    }
}
void Acceptor::setReusePort()
{
    int opt = 1;
    int ret = setsockopt(_sock.fd(), SOL_SOCKET, SO_REUSEPORT, &opt, sizeof(opt));
    if (ret == -1)
    {
        cerr << "setsockopt" << endl;
        return;
    }
}

void Acceptor::bind()
{
    int ret = ::bind(_sock.fd(), (struct sockaddr *)_addr.getAddrPtr(), sizeof(struct sockaddr));
    if (ret == -1)
    {
        perror("bind");
        return;
    }
}
void Acceptor::listen()
{
    int ret = ::listen(_sock.fd(), 128);
    if (-1 == ret)
    {
        perror("listen");
        return;
    }
    _isListening = true;
    cout << "server is listening......" << endl;
}

int Acceptor::fd()
{
    return _sock.fd();
}

void Acceptor::handleRead() // 处理新连接
{
    int connfd = accept();
    if (_newConnectionCallback)
    {
        _newConnectionCallback(_sock.fd(), connfd); 
    }
    else
    {
        cerr << "No new connection callback set.\n";
        ::close(connfd);
    }
}
